<template>
  <div>
    <el-button class="mb5" style="float: right" type="primary" @click="getList">
      <template #icon>
        <i-ep-search/>
      </template>
      刷新
    </el-button>
    <el-table v-adaptive="90" :border="true" :data="labApplyList" :header-cell-style="$headerCellStyle" :stripe="true"
              highlight-current-row>
      <el-table-column fixed="left" label="明细" type="expand">
        <template #default="props">
          <div m="4">
            <el-table :data="props.row.labItemVoList" :stripe="true" highlight-current-row>
              <el-table-column fixed="left" width="100px"/>
              <el-table-column fixed="left" label="项目代码" prop="itemCode" width="150px"/>
              <el-table-column fixed="left" label="项目名称" prop="itemName" width="180px"/>
              <el-table-column label="收费标志" width="100" :align="'center'" prop="chargeFlag" fixed="left">
                <template #default="scope">
                  <dict-data-tag :options="dictDataMap['charge_flag_dict']" :value="scope.row.chargeFlag"/>
                </template>
              </el-table-column>
              <el-table-column label="确认标志" width="80" :align="'center'" prop="confirmFlag" fixed="left">
                <template #default="scope">
                  <dict-data-tag :options="dictDataMap['confirm_flag']" :value="scope.row.confirmFlag"/>
                </template>
              </el-table-column>
              <el-table-column fixed="left" label="数量" prop="num" width="120px"/>
              <el-table-column fixed="left" label="单价(元)" prop="price" width="120px"/>
              <el-table-column fixed="left" label="总价(元)" prop="costs" width="120px"/>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="申请序号" prop="applyNo" width="120"/>
      <el-table-column :align="'center'" fixed="left" label="收费标志" prop="chargeFlag" width="120">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['charge_flag_dict']" :value="scope.row.chargeFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="确认标志" width="80" :align="'center'" prop="confirmFlag" fixed="left">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['confirm_flag']" :value="scope.row.confirmFlag"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="是否加急" prop="isUrgent">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.isUrgent"/>
        </template>
      </el-table-column>
      <!--            <el-table-column :align="'center'" label="检验类别" prop="labTypeName"/>-->
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="症状" prop="symptom" width="120"/>
      <el-table-column :align="'center'" label="体征" prop="sign" width="120"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="临床诊断" prop="clinicalDiag"
                       width="120"/>
      <el-table-column :align="'center'" label="开单时间" prop="realDate" width="130">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.realDate, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="其他诊断" :align="'center'" prop="relevantDiag" /> -->
      <el-table-column :align="'center'" label="确认人" prop="confirmUserName"/>
      <!-- <el-table-column label="取消确认" :align="'center'" prop="cancelConfirmUser" /> -->
      <el-table-column :align="'center'" label="确认时间" prop="confirmDate" width="80">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.confirmDate, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="开单科室" prop="applyDeptName"/>
      <el-table-column :align="'center'" label="执行科室" prop="implementDeptName"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" class-name="small-padding fixed-width"
                       fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-tooltip class="item" content="删除" effect="dark" placement="top">
            <el-button v-if="scope.row.confirmFlag === '1' && scope.row.chargeFlag === '1'" type="danger" circle
                       @click="handleDelete(scope.row)">
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            content="打印"
            effect="dark"
            placement="left"
          >
            <el-button circle type="primary" @click="printLabInfo(scope.row)">
              <template #icon>
                <i-ep-printer/>
              </template>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" content="查看结果" effect="dark" placement="top">
            <el-button circle
                       type="warning"
                       @click="queryViewReportFun(scope.row)"
            >
              <i-ep-view/>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :total="total" @pagination="getList"/>
  </div>

  <el-dialog v-model="open" :close-on-click-modal="false" :title="'查看检查结果'" append-to-body width="50%"
             @close="dialogClose">
    <div class="search-container mt20" style="height: 400px ;overflow-y: auto">
      <el-row>
        <el-form-item label="患者姓名：" label-width="100px">
          <span class="ys-css">{{ viewReportInfo.spatientName }}</span>
        </el-form-item>
        <el-form-item label="患者性别：" label-width="222px">
          <span class="ys-css">{{ viewReportInfo.ssex }}</span>
        </el-form-item>
        <el-form-item label="患者年龄：" label-width="180px">
          <span class="ys-css">{{ viewReportInfo.iage }}{{viewReportInfo.sageUnit}}</span>
        </el-form-item>
        <el-form-item label="开单科室：" label-width="150px">
          <span class="ys-css">{{ viewReportInfo.sapplyDeptName }}</span>
        </el-form-item>
        <el-row>
          <el-form-item label="开单医生：" label-width="100px">
            <span class="ys-css">{{ viewReportInfo.sapplyDoctorName }}</span>
          </el-form-item>
          <el-form-item label="开单时间：" label-width="150px">
            <span class="ys-css">{{ viewReportInfo.sapplyDate }}</span>
          </el-form-item>
        </el-row>
      </el-row>
      <el-table :border="true" :data="viewReportList" :header-cell-style="$headerCellStyle" :span-method="objectSpanMethod" :stripe="true"
                height="280px"  highlight-current-row>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="检查项目" prop="sapplyName" width="120"/>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="标本" prop="ssamName" width="120"/>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="项目明细" prop="sitemName"/>
        <el-table-column :align="'right'" :show-overflow-tooltip="true" label="结果值" prop="sresult" width="120"/>
        <el-table-column :align="'left'" :show-overflow-tooltip="true" label="单位" prop="sunit" width="120"/>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="范围" prop="sreviewNote" width="120"/>

      </el-table>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import {delLabApply, queryViewReport, refundApplication, selectPageLabApply} from "@/api/patient/labApply";

import {useDictStoreHook} from "@/store/modules/dict";

const dictStore = useDictStoreHook();
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "clinic_or_visit",
    "charge_flag_dict",
    "sys_yes_no",
    "position_type",
    "confirm_flag"
  )
);
const {proxy} = getCurrentInstance() as any;

const props = defineProps({
  inoroutFlag: String,
  orgId: String,
});
const queryParamsRef = ref();
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
});
const labApplyList = ref([]);
const total = ref(0);
const open = ref(false);
const clinicId = ref(proxy.$clinicId);
const patientId = ref(proxy.$patientId);

const viewReportList = ref<any>([])
const viewReportInfo = ref<any>({})

function getList() {
  if (props.inoroutFlag === "4") {
    queryParams.value.clinicId = clinicId;
  }
  queryParams.value.inoroutFlag = props.inoroutFlag;
  queryParams.value.orgId = props.orgId;
  selectPageLabApply(queryParams.value).then((response: any) => {
    labApplyList.value = response.rows;
    total.value = response.total;
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const clinicIndexIds = row.id;
  ElMessageBox.confirm("是否确认删除？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delLabApply(clinicIndexIds).then((res: any) => {
        if (res.data === 1) {
          ElMessage.success("删除成功");
        } else if (res.data === 999) {
          ElMessage.error("检验已删除");
        } else if (res.data === 998) {
          ElMessage.error("检验已确认,不能删除");
        } else if (res.data === 992) {
          ElMessage.error("检验已收费,不能删除");
        } else if (res.data === 993) {
          ElMessage.error("检验已申请退费,不能删除");
        } else if (res.data === 994) {
          ElMessage.error("检验已退费,不能删除");
        } else if (res.data === 995) {
          ElMessage.error("检验已确认退费,不能删除");
        } else if (res.data === 996) {
          ElMessage.error("检验科室确认退费中,不能删除");
        } else {
          ElMessage.error("删除失败，请联系管理员。");
        }
        getList();
      });
    })
    .catch(() => {
    });
}

/** 修改收费状态 ：3->申请退费 ;2->撤销退费 */
function refundApplicationFun(row, chargeFlag) {
  let message = "确认要进行申请退费？";
  if (chargeFlag === "2") {
    // 撤销退费
    message = "确认要进行撤销退费操作吗？";
  }
  ElMessageBox.confirm(message, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    refundApplication(row.id, chargeFlag).then((res: any) => {
      if (res.data) {
        if (chargeFlag === "2") {
          ElMessage.success("撤销退费成功。");
        } else if (chargeFlag === "3") {
          ElMessage.success("申请退费成功。");
        }
      } else {
        if (chargeFlag === "2") {
          ElMessage.success("撤销退费失败。");
        } else if (chargeFlag === "3") {
          ElMessage.error("申请退费失败。");
        }
      }
      getList();
    });
  });
}

function queryViewReportFun(row: any) {
  const param = {
    applyNo: row.applyNo,
    id: row.id,
    orgId: row.orgId,
  }
  queryViewReport(param).then((res: any) => {
    if (!res.data || res.data.length <= 0) {
      return ElMessage.error("未查询到检验结果，请稍后再次查看")
    }
    open.value = true;
    viewReportList.value = res.data;
    viewReportInfo.value = res.data[0];
  })
}


function dialogClose() {
  open.value = false;
}


/** 表格合并列和行 */
function objectSpanMethod({row, column, rowIndex, columnIndex}) {
  if (columnIndex === 0) {
    const _row = flitterData(viewReportList.value, columnIndex).one[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col,
    };
  }
}

/**合并表格的第一列，处理表格数据 */
function flitterData(arr, columnIndex) {
  let spanOneArr: any = [];
  let concatOne = 0;
  arr.forEach((item, index) => {
    if (index === 0) {
      spanOneArr.push(1);
    } else {
      //注意这里的quarterly是表格绑定的字段，根据自己的需求来改
      if (columnIndex === 0) {
        if (item.sapplyName === arr[index - 1].sapplyName) {
          //第一列需合并相同内容的判断条件
          spanOneArr[concatOne] += 1;
          spanOneArr.push(0);
        } else {
          spanOneArr.push(1);
          concatOne = index;
        }
      }
    }
  });
  return {
    one: spanOneArr,
  };
}

function printLabInfo (row: any) {
  let url = "/business/labApply/printLabInfo";
  const formData = new FormData()
  formData.append("id", row.id)
  formData.append("orgId", row.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      // objectUrl.value = URL.createObjectURL(res)
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('打印失败')
    }
  })
}

getList();
defineExpose({
  getList,
});
</script>
<script lang="ts">
export default {
  name: "applyTable",
};
</script>
